//
//  AppDelegate+IM.m
//  Keping
//
//  Created by 23 on 2017/12/8.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "AppDelegate+IM.h"
#import "GPProfileItem.h"
#import <UserNotifications/UserNotifications.h>
#import "GPContactRequest.h"
#import "GPVideoCallManager.h"
#import "KTabBarController.h"
#import "KNavigationController.h"
#import "GPChatController.h"
#import "GPIMController.h"
#import "GPChatViewModel.h"
#import "KEaseMobManager.h"

@implementation AppDelegate (IM)

/**设置UI*/
- (void)setupIM:(NSDictionary *)launchOptions
{
    //AppKey:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions* option = [EMOptions optionsWithAppkey:KHyApiKey];
    option.apnsCertName = KHyPushCerName;
    [option setIsAutoAcceptGroupInvitation:NO];
    [[EMClient sharedClient] initializeSDKWithOptions:option];
    
    //环信配置 -- 音视频配置
    EMCallOptions *options = [[EMClient sharedClient].callManager getCallOptions];
    //当对方不在线时，是否给对方发送离线消息和推送，并等待对方回应
    options.isSendPushIfOffline = YES;
    //设置视频分辨率：自适应分辨率、352 * 288、640 * 480、1280 * 720
    options.videoResolution = EMCallVideoResolutionAdaptive;
    //最大视频码率，范围 50 < videoKbps < 5000, 默认0, 0为自适应，建议设置为0
    options.maxVideoKbps = 0;
    //最小视频码率
    options.minVideoKbps = 0;
    //是否固定视频分辨率，默认为NO
    options.isFixedVideoResolution = NO;
    [[EMClient sharedClient].callManager setCallOptions:options];
    
    
    //推送选项
    EMPushOptions *pushoptions = [[EMClient sharedClient] pushOptions];
    pushoptions.displayStyle = EMPushDisplayStyleMessageSummary; // 显示消息内容
    // options.displayStyle = EMPushDisplayStyleSimpleBanner // 显示“您有一条新消息”
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        EMError *error = [[EMClient sharedClient] updatePushOptionsToServer]; // 更新配置到服务器，该方法为同步方法，如果需要，请放到单独线程
        if(!error) {
            // 成功
        }else {
            // 失败
        }
    });
    
    //注册消息接收代理
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].callManager setBuilderDelegate:self];  //离线发送通话推送回调
    //创建callmanager
    [GPVideoCallManager shareManager];
    
    
    UIApplication *application = [UIApplication sharedApplication];
    
    //iOS10 注册APNs
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        
        
        UNAuthorizationOptions options = UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
        
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError *error) {
            if (granted) {
#if !TARGET_IPHONE_SIMULATOR
                dispatch_async(dispatch_get_main_queue(), ^{
                    [application registerForRemoteNotifications];
                });
#endif
            }
        }];
        return;
    }
    
    if([application respondsToSelector:@selector(registerUserNotificationSettings:)])
    {
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    
#if !TARGET_IPHONE_SIMULATOR
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
    }else{
        UIRemoteNotificationType options = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:options];
    }
#endif
    
    
    if (launchOptions) {
        //收到通知，点击通知后打开的应用程序 --- 跳转到消息中心
        //从appstore直接打开 - 也会执行这个方法  --- 所以需要判断是否登录
        NSString *phone = launchOptions[@"f"];
        NSString *name = @"";
        NSString *uid = @"";
        [self kl_jumpToMessageVC:phone name:name uid:uid];
    }
    
    
}

/**APP进入后台*/
- (void)gp_applicationDidEnterBackground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

/**APP将要从后台返回*/
-(void)gp_applicationWillEnterForeground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


#pragma mark - EMChatManagerDelegate
/**接收到消息后的回调*/
- (void)messagesDidReceive:(NSArray *)aMessages
{
    //解析普通消息
    for (EMMessage *message in aMessages) {
        
        //获取环信id(电话号码)
        __block NSString *hid = message.from;
        
        BOOL isExist = [GPProfileItem isRecordExist:hid];
        if (isExist) {
            continue;
        }
        
        //请求用户个人信息
        NSString *url = [@"/intelligentcommunity/api/biz/ou/v1/partys/getPhone/{phone}.htm" stringByReplacingOccurrencesOfString:@"{phone}" withString:hid];
        GPContactRequest *request = [[GPContactRequest alloc] initWithURL:url];
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            
            NSDictionary *dict = request.responseJSONObject;
            NSDictionary *partyView = dict[@"partyView"];
            NSLog(@">>>>>>>>>>>>>smallyou:获取用户消息--->%@", partyView);
            //创建GPProfileItem
            GPProfileItem *item = [[GPProfileItem alloc] init];
            item.uid  = partyView[@"id"];
            item.hid  = partyView[@"phone"];
            item.name = partyView[@"nickName"];
            item.phone = partyView[@"phone"];
            item.avatarURL = partyView[@"profile"];
            item.realName = partyView[@"realName"];
            item.isBlock = partyView[@"isBlock"];
            item.remarks = partyView[@"remarks"];
            [item insertToDatabase];
            //发起通知
            [GPNoticationHelp postNotificationName:kBuddyUserInfoUpdatedNotificaiton object:nil];
            
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            NSLog(@">>>>>>>>>>>>>smallyou:获取用户消息失败--->%@", request);
        }];
        
    }
    
    EMMessage *message = aMessages.firstObject;
    EMMessageBody *firstMessageBody = message.body;
    BOOL isSOS = NO;
    switch (firstMessageBody.type) {
        case EMMessageBodyTypeText:
        {
            EMTextMessageBody *textBody = (EMTextMessageBody *)firstMessageBody;
            if ([textBody.text isEqualToString:@"SOS test"]) {
                //SOS 消息
                isSOS = YES;
            }
        }
            break;
        case EMMessageBodyTypeImage:
        {
            EMImageMessageBody *imgMessageBody = (EMImageMessageBody *)firstMessageBody;
            //判断是否是SOS紧急消息
            NSDictionary *ext = message.ext;
            if (ext == nil || ![ext.allKeys containsObject:@"latitude"] || ![ext.allKeys containsObject:@"longitude"] ) {
                isSOS = NO;
            }else{
                isSOS = YES;
               
            }
            
            
        }
            break;
        case EMMessageBodyTypeLocation:
        {
            EMLocationMessageBody *locationBody = (EMLocationMessageBody *)firstMessageBody;
            if ([locationBody.address isEqualToString:@"SOS test"]) {
                //SOS 消息
                isSOS = YES;
            }
        }
            break;
        default:
            break;
    }
    
    
    //如果当前是APP是在后台，发起本地推送
    UILocalNotification *noti = [[UILocalNotification alloc] init];
    if (noti && ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)) {
        //设置推送时间
        noti.fireDate = [NSDate new];//=now
        
        //设置时区
        noti.timeZone = [NSTimeZone defaultTimeZone];
        
        //设置重复间隔
        noti.repeatInterval = 0;
        
        //推送声音
        noti.soundName = UILocalNotificationDefaultSoundName;
        
        //内容
        noti.alertBody = @"You have a new message";
        noti.alertTitle = isSOS?@"":@"Friend";
        
        //设置userinfo 方便在之后需要撤销的时候使用
        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        noti.userInfo = infoDic;
        
        //添加推送到uiapplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:noti];
    }
    
    
    //发出通知
    [GPNoticationHelp postNotificationName:@"kChatReceivedMessageNotification" object:nil];
}


#pragma mark - EMCallBuilderDelegate
- (void)callRemoteOffline:(NSString *)aRemoteName
{
    NSString *text = [[EMClient sharedClient].callManager getCallOptions].offlineMessageText;
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
    NSString *fromStr = [EMClient sharedClient].currentUsername;
    EMMessage *message = [[EMMessage alloc] initWithConversationID:aRemoteName from:fromStr to:aRemoteName body:body ext:@{@"em_apns_ext":@{@"em_push_title":text}}];
    message.chatType = EMChatTypeChat;
    
    [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:nil];
}


- (void)kl_jumpToMessageVC:(NSString *)phone name:(NSString *)name  uid:(NSString *)uid{
    
    
    if (![self isUserLogin]) {
        return;
    }
    
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive) {
        KTabBarController *tabBarVC = (KTabBarController *)self.window.rootViewController;
        KNavigationController *navVC = tabBarVC.viewControllers[tabBarVC.selectedIndex];
     
        for (UIViewController *vc in navVC.childViewControllers) {
            if ([vc.class isKindOfClass:[GPIMController class]]) {
                return;
            }
        }
        
        GPIMController *vc = [[GPIMController alloc] init];
        [navVC pushViewController:vc animated:NO];
    }
}


-(BOOL)isUserLogin{
    BOOL login = NO;
    KLog(@"登录ID:%@",[KAppConfig sharedConfig].logined ? @"YES":@"NO");
    KLog(@"环信登录ID:%@",[EMClient sharedClient].isLoggedIn ? @"YES":@"NO");
    if ([KAppConfig sharedConfig].logined ) {//&& [EMClient sharedClient].isLoggedIn
        [KEaseMobManager easeMobLoginUsername:[KAppConfig sharedConfig].phone password:[KAppConfig sharedConfig].password controller:nil];
        login = YES;
        if (![[KAppConfig sharedConfig].sessionId isNotBlank]) {
            login = NO;
        }
    }
    return login;
}



@end
